package com.huike;

import com.huike.common.utils.uuid.UUID;
import io.minio.*;
import io.minio.errors.MinioException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MinioTest {
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        uploadFile();
//        String str="AAAA.AA.VV.png";
//        String substring = str.substring(str.lastIndexOf("."));
//        System.out.println(substring);
    }

    private static void uploadFile() throws InvalidKeyException, IOException, NoSuchAlgorithmException {
        try {
            //你的endpoint,本机可以不变
            String endpoint = "http://localhost:9000";
            //你的accessKey
            String accessKey = "minioadmin";
            //你的sercetKey
            String secretKey = "minioadmin";
            //你的bucket
            String bucketName = "contract";
            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey).build();

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket("contract").build());
            if (!isExist) {
                // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("contract").build());
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            String date = sdf.format(new Date());

            //找一个你电脑上图片的绝对路径,最好是PNG图片
            File file = new File("E:\\imgs\\db_reggie.sql");
            long size = file.length();
            String fileName = file.getName();


            //你也可以自定义上传文件的路径，这样设置是为了更好的管理
            String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 6);

            String fileUploadPath = date + uuid + fileName.substring(fileName.lastIndexOf("."));


            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileUploadPath)
                    .stream(new FileInputStream(file), size, -1)
                    //.contentType("image/png")
                    .build();

            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);

            System.out.println(file.getAbsolutePath() + "is successfully uploaded as 【" + fileUploadPath + "】 to 【" + bucketName + "】bucket.");
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }
}
